from sqlalchemy import Boolean, Column, Integer, String,DateTime
from sqlalchemy.orm import relationship
from src.database.db import Base
from datetime import datetime

class Captcha(Base):
    __tablename__ = "captchas"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, index=True)
    code = Column(String)
    created_at = Column(DateTime, default=datetime.utcnow)
    is_used = Column(Boolean, default=False)

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, index=True)
    username = Column(String, unique=True, index=True, primary_key=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)

    # 修改后的关系配置
    sessions = relationship(
        "Session", 
        back_populates="user",
        cascade="all, delete-orphan",
        passive_deletes=True,
        # 只加载user_id不为NULL的会话
        primaryjoin="and_(User.username==Session.username, Session.username.isnot(None))"
    )